/**
 * Copyright (c) 2019-2021,  陈俊兵 (cjb6b.com@gmail.com)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ktjiaoyu.advance.cas;

import java.util.concurrent.atomic.AtomicStampedReference;

/**
 *
 * @packageName com.ktjiaoyu.advance.cas
 * @fileName AtomicStampedReferenceTest.java
 * @author 陈俊兵 (cjb6b.com@gmail.com)
 * @createTime 2023/7/25 23:31
 * @lastModify 2023/7/25 23:31
 * @version 1.0.0
 */
public class AtomicStampedReferenceTest {

    static AtomicStampedReference<Integer> stampedReference =
            new AtomicStampedReference<>(10000, 1);

    public static void main(String[] args) {
        new Thread(()->{
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Integer oldVal = stampedReference.getReference();

            stampedReference.compareAndSet(oldVal, 5000, stampedReference.getStamp(),
                    stampedReference.getStamp() + 1);

            System.out.println(Thread.currentThread().getName() + "提取公款：公账"+oldVal+"元变为->" + stampedReference.getReference() + "元");

            oldVal = stampedReference.getReference();
            stampedReference.compareAndSet(oldVal, 5000, stampedReference.getStamp(),
                    stampedReference.getStamp() + 1);
            System.out.println(Thread.currentThread().getName() + "还回公款：公账"+oldVal+"元变为->" + stampedReference.getReference() + "元");
        },"张三").start();

        new Thread(()->{
            // 获取版本
            int stamp = stampedReference.getStamp();
            Integer oldVal = stampedReference.getReference();
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("原始版本" + stamp + ", 新版本" + stampedReference.getStamp());
            if(stampedReference.compareAndSet(oldVal, 5000,
                    stamp, stamp + 1)){
                // 只有对上账才能修改
                System.out.println(Thread.currentThread().getName() + "提取公款：公账"+oldVal+"元变为->" + stampedReference.getReference() + "元");
            }else{
                System.out.println(Thread.currentThread().getName()+"报警，有人挪用公款！");
            }

        },"老板").start();
    }
}
